package com.mrtaohuan.action.admin;

import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.json.JSONObject;

import com.google.inject.Inject;
import com.mrtaohuan.data.dao.UserDAO;
import com.mrtaohuan.data.entity.ResponseData;
import com.mrtaohuan.data.entity.User;
import com.mrtaohuan.render.HttpContext;
import com.mrtaohuan.render.freemarker.AbstractFreeMarkerRender;
import com.mrtaohuan.render.freemarker.FreeMarkerRenderer;
import com.mrtaohuan.render.freemarker.Templates;
import com.mrtaohuan.util.Strings;

@Path("/login")
public class Login {

	@Inject
	HttpContext context;
	@Inject
	UserDAO userDAO;

	@GET
	@Produces(MediaType.TEXT_HTML)
	public String login() {
		final AbstractFreeMarkerRender renderer = new FreeMarkerRenderer();
		renderer.setTemplateName("admin/login");
		renderer.setContext(context);
		return renderer.renderHtml();
	}

	@Path("/action")
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	public String loginAction(@QueryParam("email") String email,
			@QueryParam("password") String password) {

		final ResponseData data = new ResponseData(0, "ERROR Incorrect email address or password", null);
		if (Strings.isEmail(email) && !Strings.isNullOrEmpty(password)) {
			final User user = userDAO.get(email);
			if (user != null && user.getPassword().equals(password)) {
				context.getRequest().getSession().setAttribute("user", user.getEmail());
				data.setCode(1);
				data.setMsg("Login Success");
				data.setOjb(user);
			}
		}
		return new JSONObject(data).toString();
	}
	
	@Path("/out")
	@GET
	@Produces(MediaType.TEXT_HTML)
	public String logout(@QueryParam("go") String go){
		if(Strings.isNullOrEmpty(go)){
			go = "/login";
		}
		final HttpSession session = context.getRequest().getSession();
		if(session.getAttribute("user")!=null){
			session.removeAttribute("user");
		}
		return "<script type=\"text/javascript\">window.location.href='"+go+"'</script>";
	}
}
